package com.fsm_demo.syncDemo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*******************
 *@Describe
 *@author 封神梦
 *@Time 2022/6/24
 *@Company http://com.yiview.com
 ****************/
public class ReadWriteWithLockDemo {
    public static void main(String[] args) {
        MyCache2 myCache = new MyCache2();
        for (int i = 0; i <=5 ; i++) {
            final Integer tempInt = i;
            new Thread(()->{
                myCache.put(tempInt.toString(),tempInt);
            },"写线程操作："+i).start();
        }
        for (int i = 0; i <=5 ; i++) {
            final Integer tempInt = i;
            new Thread(()->{
                myCache.get(tempInt.toString() );
            },"读线程操作："+i).start();
        }
    }
}

class MyCache2{
    private volatile Map<String,Object> map = new HashMap<>();

    private  final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void put(String key,Object value){
        rwLock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"===>开始写入："+key);
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        map.put(key, value);
        System.out.println(Thread.currentThread().getName()+"===>写入完成："+key);
        rwLock.writeLock().unlock();
    }

    public void get(String key){
        rwLock.readLock().lock();

        System.out.println(Thread.currentThread().getName()+"===>开始读取："+key);
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       Object  value = map.get(key );
        System.out.println(Thread.currentThread().getName()+"===>读取完成："+key);
        rwLock.readLock().unlock();
    }

}
